import { store } from "@/store";
import { defineStore } from "pinia";
import ExpressAPI, {
  type ExpressListQuery,
  type ExpressType,
  type ExpressForm,
} from "@/api/logistics/express";

export const useExpressStore = defineStore("express", () => {
  const list = ref<ExpressType[]>([]);
  const totalCount = ref(0);
  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchExpressList(params: ExpressListQuery) {
    loading.list = true;
    const response = await ExpressAPI.getExpressList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateExpress(data: Partial<ExpressForm>) {
    loading.create = true;
    await ExpressAPI.createExpress(data);
    loading.create = false;
  }

  async function fetchUpdateExpress(data: Partial<ExpressForm>) {
    loading.update = true;
    await ExpressAPI.updateExpress(data);
    loading.update = false;
  }

  async function fetchDeleteExpress(id: number) {
    loading.delete = true;
    await ExpressAPI.deleteExpress(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchExpressList,
    fetchCreateExpress,
    fetchUpdateExpress,
    fetchDeleteExpress,
  };
});

export const useExpressStoreHook = () => {
  return useExpressStore(store);
};
